//
//  HMMainTabBar.swift
//  新浪微博-4-8v1.0
//
//  Created by 黎永锋 on 16/4/8.
//  Copyright © 2016年 黎永锋. All rights reserved.


import UIKit

class HMMainTabBar: UITabBar {

    //定义闭包属性,传递加号点击事件
    var composeClosure: (() -> ())?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let buttonCount = HMMainTabBarButtonCount
        
        //宽度
        let width = self.frame.size.width / CGFloat(buttonCount)
        
        //创建frame
        let newFrame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
        
        var index = 0
        for subView in subviews{
        
            // 只想重新设置 UITabBarButton 的 frame
            if subView.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                //frame可以平移,CGRectOffset
                subView.frame = CGRectOffset(newFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
            }
        }
        
        //设置加号按钮的frame
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.size.height)
    }
    
    //MARK: -按钮点击事件
    //@objc: 让OC可以调用我们swift的方法,系统默认会为所有的swift方法加上@objc,如果方法加了private,就不会帮我们加@objc
    @objc private func didClickComposeButton(){
    
//        print("hello")
        //调用闭包
        composeClosure?()
    }
    
    // MARK: - 懒加载
    //加号按钮
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        //设置
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: Selector("didClickComposeButton"), forControlEvents: UIControlEvents.TouchUpInside)
        
        //添加按钮到tabBar
        self.addSubview(button)
        
        return button
    }()
}
